﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

using Gurucore.Framework.Core;

namespace Gurucore.Framework.DataAccess.Persistence
{
	public class ComplexDTOTransformer : DTOTransformer
	{
		public override List<T> Transform<T>(System.Data.IDataReader p_oReader, T p_sample)
		{
			List<T> arrDTO = new List<T>();
			Type oResultType = typeof(T);

			ComplexTypeInfoManager oComplexTypeInfoMgr = Application.GetInstance().GetGlobalSharedObject<ComplexTypeInfoManager>();
			ComplexTypeInfo complexTypeInfo = oComplexTypeInfoMgr.GetComplexTypeInfo(oResultType);

			SingleDTOTransformer singleTransformer = new SingleDTOTransformer();

			while (p_oReader.Read())
			{
				T oResult = null;

				List<object> propValues = new List<object>();
				foreach (PropertyInfo prop in complexTypeInfo.Elements)
				{
					object instance = singleTransformer.Transform(prop.PropertyType, null, p_oReader);
					propValues.Add(instance);
				}

				oResult = (T)Activator.CreateInstance(oResultType, propValues.ToArray());
				arrDTO.Add(oResult);
			}

			return arrDTO;
		}
	}
}
